package org.gp.demo.classload;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class MyClassLoad extends ClassLoader {
	static final String classFilePath = "F:/demo/Demo.class";

	@Override
	protected  Class<?> findClass(String name) throws ClassNotFoundException {
		// TODO Auto-generated method stub
		try {
			FileInputStream fis = new FileInputStream(new File(classFilePath));
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			int ch;
			while ((ch = fis.read()) != -1) {
				byte b = (byte) ch;
				bos.write(b);
			}
			byte[] classByte = bos.toByteArray();
			bos.close();
			fis.close();
			return defineClass(null, classByte, 0, classByte.length, null);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return super.findClass(name);
	}

	public static void main(String[] args) {
		ClassLoader mc=new MyClassLoad();
		try {
			Class<?> c=mc.loadClass("");
			Method m=c.getMethod("main", String[].class);
			m.invoke(null, (Object)new String[]{});
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
